package com.hy.springboot.common.utils;

import javax.crypto.Cipher;
import java.security.*;
import java.util.Base64;

/**
 * @author lccsetsun
 * @since 2024/1/31 11:21
 **/
public class RsaUtils {
		public static void main(String[] args) throws Exception {
			String plainText = "Hello, World!";

			// 生成密钥对
			KeyPair keyPair = generateKeyPair();

			// 获取公钥和私钥
			PublicKey publicKey = keyPair.getPublic();
			String publicv = Base64.getEncoder().encodeToString(publicKey.getEncoded());
			PrivateKey privateKey = keyPair.getPrivate();
			String privatev = Base64.getEncoder().encodeToString(privateKey.getEncoded());
			System.out.println(publicv +" \n"+privatev);
//			// 使用公钥加密
//			byte[] encryptedBytes = encrypt(plainText, publicKey);
//			String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
//			System.out.println("Encrypted Text: " + encryptedText);
//
//			// 使用私钥解密
//			byte[] decryptedBytes = decrypt(encryptedBytes, privateKey);
//			String decryptedText = new String(decryptedBytes);
//			System.out.println("Decrypted Text: " + decryptedText);
//
//			// 使用私钥签名
//			byte[] signatureBytes = sign(plainText, privateKey);
//			String signatureText = Base64.getEncoder().encodeToString(signatureBytes);
//			System.out.println("Signature: " + signatureText);
//
//			// 使用公钥验证签名
//			boolean isVerified = verify(plainText, signatureBytes, publicKey);
//			System.out.println("Signature Verified: " + isVerified);
		}

		public static KeyPair generateKeyPair() throws Exception {
			KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
			keyPairGenerator.initialize(2048); // 密钥长度为2048位
			return keyPairGenerator.generateKeyPair();
		}

		public static byte[] encrypt(String plainText, PublicKey publicKey) throws Exception {
			Cipher cipher = Cipher.getInstance("RSA");
			cipher.init(Cipher.ENCRYPT_MODE, publicKey);
			return cipher.doFinal(plainText.getBytes());
		}

		public static byte[] decrypt(byte[] encryptedBytes, PrivateKey privateKey) throws Exception {
			Cipher cipher = Cipher.getInstance("RSA");
			cipher.init(Cipher.DECRYPT_MODE, privateKey);
			return cipher.doFinal(encryptedBytes);
		}

		public static byte[] sign(String plainText, PrivateKey privateKey) throws Exception {
			Signature signature = Signature.getInstance("SHA256withRSA");
			signature.initSign(privateKey);
			signature.update(plainText.getBytes());
			return signature.sign();
		}

		public static boolean verify(String plainText, byte[] signatureBytes, PublicKey publicKey) throws Exception {
			Signature signature = Signature.getInstance("SHA256withRSA");
			signature.initVerify(publicKey);
			signature.update(plainText.getBytes());
			return signature.verify(signatureBytes);
		}
}
